// 2025/4/5
// https://leetcode.cn/problems/3sum-closest/description/
// 最接近的三数之和

class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            int n = nums.size();
            int ans = nums[0] + nums[1] + nums[2], dif = abs(target - ans);
            for(int i = 0; i < n - 2; i++)
            {
                int left = i + 1, right = n - 1;
                while(left < right)
                {
                    int tmp = nums[i] + nums[left] + nums[right];
                    if(abs(target - tmp) < dif)
                    {
                        ans = tmp;
                        dif = abs(target - tmp);
                    }
                    if(tmp > target) right--;
                    else if(tmp < target) left++;
                    else return tmp;
                }
            }
            return ans;
        }
    };